#include "../glob.h"
#include "mq.h"
#include <mqueue.h>
#include <pthread.h>
#include <errno.h>



#define MQ_NAME "/msg.queue"

mqd_t mqd;

int thread_routine(void * args)
{
	int rcv_len = -1;
	unsigned int prio;
	char rcv_buff[128];
	
	fd_set     set;
	struct     timeval   tv; 
	
		
	
	DEBUG("****");	


	while(1)
	{
		
		memset(rcv_buff,0,sizeof(rcv_buff));
		tv.tv_sec   =   3;  
		tv.tv_usec   =   0;
		FD_ZERO(&set);
		FD_SET(mqd,   &set);
		
		if (select(mqd   +   1,   &set,   NULL,   NULL,   &tv) > 0)
		{
			DEBUG("...");
			if   (FD_ISSET(mqd,   &set))
			{
				rcv_len = mq_receive(mqd,rcv_buff,sizeof(rcv_buff),&prio);
			}
			
			
		
		}
		else
		{
			rcv_len = -1;
		}
		
		
		DEBUG("rcv_len...%d",rcv_len);
	}

	return 0;
}


int main(int argc, char* argv[])
{
	
	struct mq_attr qa;
	pthread_t td;
	
	mq_unlink(MQ_NAME);
	
	qa.mq_maxmsg = 10;
	qa.mq_msgsize = 128;
	
	DEBUG("start...");
	
	mqd = mq_open(MQ_NAME,O_CREAT|O_EXCL|O_RDWR,0666,&qa);
	//mqd = mq_open(MQ_NAME,O_CREAT|O_RDWR);
	//mq_getattr(mqd,&qa);
	
	if (mqd <= 0)
	{
		DEBUG("error is %s",strerror(errno));
		
		return 0;
	}
	
	DEBUG("mqd=%d",mqd);
	
	pthread_create(&td, NULL, (void*)thread_routine, NULL);
	
	pthread_join(td, NULL);
	
	mq_close(mqd);

	return 0;
}
